<?php
/**
 * @copyright Copyright (c) 2021 勾股工作室
 * @license https://opensource.org/licenses/Apache-2.0
 * @link https://www.gougucms.com
 */

declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\BaseController;
use app\admin\model\Withdraw as WithdrawModel;
use app\admin\validate\WithdrawValidate;
use app\common\controller\WxPay;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\View;

class Withdraw extends BaseController

{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new WithdrawModel();
        $this->uid = get_login_admin('id');
    }
    /**
     * 数据列表
     */
    public function datalist()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $where = [];
            $where[] = ["delete_time","=",0];
            if (!empty($param['nickname'])) {
                $ids = Db::name('shop')->where([['name','like',"%{$param['nickname']}%"]])->column('uid');
                $where[] = ['uid','in',$ids];
            }
            if (!empty($param['mobile'])) {
                $uids = Db::name('user')->where([['mobile','like',"%{$param['mobile']}%"]])->column('id');
                $where[] = ['uid','in',$uids];
            }
            if (!empty($param['status'])) {
                $where[] = ['status','=',$param['status']];
            }
            $list = $this->model->getWithdrawList($where,$param);
            return table_assign(0, '', $list);
        }
        else{
            return view();
        }
    }

    /**
     * 审核
     */
    public function examine()
    {
        $param = get_params();
        $data = Db::name('withdraw')->where('id',$param['id'])->find();
        if (empty($data)) {
            return error('未找到该记录');
        }
        if ($data['status'] != 1) {
            return error('该提现已处理');
        }
        $save['update_time'] = time();
        if ($param['type'] == 1) {
            $save['status'] = 2;
            //企业付款到零钱
            $WxPay = new WxPay();
            $order_no = date('YmdHis').rand(100,999);
            $amount = $data['dz_money'];
            if ($data['tx_type'] == 1) {
                $openid = Db::name('user_one')->where('id',$data['uid'])->value('openid');
            } elseif ($data['tx_type'] == 2) {
                $openid = Db::name('user_two')->where('id',$data['uid'])->value('openid');
            } else {
                $openid = Db::name('user_three')->where('id',$data['uid'])->value('openid');
            }
            if (empty($openid)) {
                return error('提现失败,当前账号未授权微信,openid为空');
            }
            $res = $WxPay->zhuan($openid,$order_no,$amount*100,'微信提现');
            //结果打印
            if($res['result_code']=="SUCCESS"){
                Db::name('withdraw')->where('id',$param['id'])->update($save);
                return success('提现成功');
            }elseif ($res['err_code']=="SENDNUM_LIMIT"){
                return error('提现失败,每日仅能提现一次');
            }else{
                return error('提现失败,'.$res['err_code_des']);
            }
        } else {
            $save['status'] = 3;
            $save['refuse'] = $param['refuse'];
            $insert = [
                'user_type' => $data['tx_type'],
                'uid' => $data['uid'],
                'title' => '提现拒绝返回',
                'num' => $data['money'],
                'status' => 1,
                'create_time' => time(),
            ];
            if ($data['tx_type'] == 1) {
                //售酒端
                Db::name('user_one')->where('id',$data['uid'])->inc('wallet',floatval($data['money']))->update();
            }
            if ($data['tx_type'] == 2) {
                //售酒机
                Db::name('user_two')->where('id',$data['uid'])->inc('wallet',floatval($data['money']))->update();
            }
            if ($data['tx_type'] == 3) {
                //补酒员
                Db::name('user_three')->where('id',$data['uid'])->inc('wallet',floatval($data['money']))->update();
            }
            Db::name('wallet_log')->insert($insert);
            Db::name('withdraw')->where('id',$param['id'])->update($save);
            return success('操作成功');
        }
    }

    /**
     * 添加
     */
    public function add()
    {
        if (request()->isAjax()) {
            $param = get_params();

            // 检验完整性
            try {
                validate(WithdrawValidate::class)->check($param);
            } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                return to_assign(1, $e->getError());
            }

            $this->model->addWithdraw($param);
        }else{
            return view();
        }
    }


    /**
     * 编辑
     */
    public function edit()
    {
        $param = get_params();

        if (request()->isAjax()) {
            // 检验完整性
            try {
                validate(WithdrawValidate::class)->check($param);
            } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                return to_assign(1, $e->getError());
            }

            $this->model->editWithdraw($param);
        }else{
            $id = isset($param['id']) ? $param['id'] : 0;
            $detail = $this->model->getWithdrawById($id);
            if (!empty($detail)) {
                View::assign('detail', $detail);
                return view();
            }
            else{
                throw new \think\exception\HttpException(404, '找不到页面');
            }
        }
    }


    /**
     * 查看信息
     */
    public function read()
    {
        $param = get_params();
        $id = isset($param['id']) ? $param['id'] : 0;
        $detail = $this->model->getWithdrawById($id);
        if (!empty($detail)) {
            if ($detail['tx_type'] == 1) {
                $user = Db::name('user_one')->where('id',$detail['uid'])->find();
            } elseif ($detail['tx_type'] == 2) {
                $user = Db::name('user_two')->where('id',$detail['uid'])->find();
            } else {
                $user = Db::name('user_three')->where('id',$detail['uid'])->find();
            }
            $detail['phone'] = $user['mobile'];
            $detail['nickname'] = $user['user_name'];
            if ($detail['status'] == 1) {
                $detail['status_title'] = '待审核';
            } elseif ($detail['status'] == 2) {
                $detail['status_title'] = '已通过';
            } else {
                $detail['status_title'] = '未通过';
            }
            View::assign('detail', $detail);
            return view();
        }
        else{
            throw new \think\exception\HttpException(404, '找不到页面');
        }
    }

    /**
     * 删除
     * type=0,逻辑删除，默认
     * type=1,物理删除
     */
    public function del()
    {
        $param = get_params();
        $id = isset($param['id']) ? $param['id'] : 0;
        $type = isset($param['type']) ? $param['type'] : 0;

        $this->model->delWithdrawById($id,$type);
    }
}
